//自动下载时的遮罩层
var loadMask, autoRefreshReq;
var $gridList;
require(['grid', 'topBar', 'layout', 'date'], function () {
    var postData = {};
    $('#top').topBar({
        left: [{
            type: 'filter',
            search: function () {
                if (getPostData()) {
                    $('#grid').grid('setGridParam', {
                        datatype: "json",
                        postData: postData
                    }).trigger("reloadGrid");
                    autoRefresh();
                }
            },
            item: [
                {
                    text: '时间段',
                    name1: 'beginTime',
                    name2: 'endTime',
                    format: 'yyyy-MM-dd HH:mm:ss',
                    type: 'dateLine'
                },
                {
                    text: '车身部件',
                    name: 'componentType',
                    type: 'item-select',
                    data: [
                        {text: '发动机', value: '01'}
                    ]
                }
            ]
        }],
        right: [
            {
                text: '文件导出',
                type: 'btn',
                click: function () {
                    var selectRowIds = $gridList.getGridParam().selarrrow;
                    var fileNames = [];
                    $.each(selectRowIds, function (index, item) {
                        var row = $gridList.getRowData(item);
                        if (row.fileSt == '已下载') {
                            fileNames.push(row.fileName);
                        }
                    });
                    if (fileNames.length != 1) {
                        $.messager.alert("提示", "请选择1个已下载完成的文件进行导出", "info");
                        return;
                    }
                    var url = "/engineManage/getEngineFile.htm";
                    $.exportFile(url, {fileNames: fileNames});
                }
            },
            {
                text: '数据分析',
                type: 'btn',
                click: function () {
                    dataAnalysis();
                }
            },
            {
                text: '文件下载',
                type: 'btn',
                click: function () {
                    fileUpLoad();
                }
            }
        ]
    });

    $('body').layout();

    //grid
    $gridList = $('#grid');

    $gridList.grid({
        url: "/engineManage/searchLoadFileRcd.htm",
        multiselect: true,
        showPager: false,
        colModel: [
            {name: "fileName", index: "fileName", label: '文件名', key: true, width: 150},
            {
                name: "fileSt", index: "fileSt", label: '文件状态', width: 80,
                formatter: function (cellval) {
                    var val = '等待下载';
                    switch (cellval) {
                        case '1':
                            val = '下载中';
                            break;
                        case '2':
                            val = '下载失败';
                            break;
                        case '3':
                            val = '已下载';
                            break;
                    }
                    return val;
                }
            },
            {name: "failInfo", index: "failInfo", label: '状态描述', width: 350},
            {
                name: "genTime", index: "genTime", label: '下载时间', width: 120, formatter: function (cellval) {
                if (cellval) {
                    return new Date(cellval).format('yyyy-MM-dd hh:mm:ss');
                }
            }
            }
        ]
    });

    //获取需要传递到后台的参数
    function getPostData() {
        var selectedNodes;
        selectedNodes = commonFun.getLeftTreeSelectedNodes();
        if (!selectedNodes.length) {
            $.messager.alert("提示", "请先选择左侧树的一辆车辆!", "warning");
            return false;
        } else {
            if (selectedNodes[0].type !== "CAR") {
                $.messager.alert("提示", "请先选择左侧树的一辆车辆!", "warning");
                return false;
            }
        }
        postData = $("#top").parent().getValues();
        var beginTime = new Date(postData.beginTime);
        var endTime = new Date(postData.endTime);
        if ((beginTime - endTime) > 0) {
            $.messager.alert("提示", "开始时间晚于结束时间!", "warning");
            return false;
        }
        if ((endTime - beginTime) > (1000 * 45 * 60)) {
            $.messager.alert("提示", "时间间隔不得大于45分钟!", "warning");
            return false;
        }
        postData.carIds = selectedNodes[0].id;
        return true;
    };

    //文件下载
    function fileUpLoad() {
        if (getPostData()) {
            var selectRowIds = $gridList.getGridParam().selarrrow;
            var fileNames = [];
            $.each(selectRowIds, function (index, item) {
                var row = $gridList.getRowData(item);
                if (row.fileSt != '已下载') {
                    fileNames.push(row.fileName);
                }
            });
            if (fileNames.length == 0) {
                $.messager.alert("提示", "请选择等待下载的文件", "info");
                return;
            }
            $.ajaxExt({
                url: "/engineManage/loadFiles.htm",
                data: {
                    carIds: postData.carIds,
                    fileNames: fileNames.join(','),
                    componentType: $gridList.getGridParam().postData.componentType
                }
            }).done(function () {
                //createLoadMask();
                autoRefresh();
            });
        }
    }

    //文件下载时自动刷新各个文件的状态
    function autoRefresh() {
        var fileNames = [];
        var selectRowIds = $('#grid').getGridParam().selarrrow;
        $.each(selectRowIds, function (index, item) {
            var row = $gridList.getRowData(item);
            if (row.fileSt != '已下载') {
                fileNames.push(row.fileName);
            }
        });
        if (autoRefreshReq) {//如果之前的请求还在，取消之前的请求
            autoRefreshReq.abort();
        }
        autoRefreshReq = $.ajaxExt({
            url: "/engineManage/getLoadFileSt.htm",
            data: {
                fileNames: fileNames.join(','),
                beginTime: $gridList.getGridParam().postData.beginTime,
                endTime: $gridList.getGridParam().postData.endTime,
                carIds: $gridList.getGridParam().postData.carIds,
                componentType: $gridList.getGridParam().postData.componentType
            }
        }).done(function (result) {
            autoRefreshReq = null;
            if ($.isArray(result)) {
                var complete = true;
                $.each(result, function (index, item) {
                    $gridList.setRowData(item.fileName, item);
                    if (item.fileSt == '0' || item.fileSt == '1') {
                        setTimeout(autoRefresh, 4000);
                        complete = false;
                    }
                    if (complete) {
                        //  clearLoadMask();
                    }
                })
            } else {
                //  clearLoadMask();
            }
        });
    }


    //数据分析页面跳转
    function dataAnalysis() {
        if (getPostData()) {
            var data = {
                orgIds: postData.carIds,
                type: 'CAR',
                beginTime: postData.beginTime.substring(0, 10),
                endTime: postData.endTime.substring(0, 10) + "  23:59:59"
            };
            $.openTab('1acb6858b6364ac3a63cbf70c77da8f0', 'autoSearch', [data]);
        }
    }

})
